package com.school.movie.business.web.controller;


import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.api.ApiController;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.school.movie.business.web.model.pojo.MovieVideo;
import com.school.movie.business.web.model.vo.Manager;
import com.school.movie.business.web.model.vo.MovieVo;
import com.school.movie.common.bean.PageBean;
import com.school.movie.common.utils.ContextUtils;
import com.school.movie.common.utils.MediaUtil;
import com.school.movie.common.utils.PageUtil;
import com.school.movie.service.MovieVideoService;
import com.school.movie.service.imp.MovieServiceImpl;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import javax.inject.Inject;
import javax.validation.Valid;
import java.io.File;
import java.io.IOException;
import java.io.Serializable;
import java.sql.Timestamp;
import java.time.Instant;
import java.util.Collection;
import java.util.List;
import java.util.Objects;
import java.util.UUID;

/**
 * (MovieVideo)表控制层
 *
 * @author makejava
 * @since 2021-01-27 20:14:34
 */
@RequestMapping("video")
@Controller
public class MovieVideoController extends ApiController {

    @Inject
    private MovieVideoService movieVideoService;
    @Inject
    private MovieServiceImpl movieService;
    @Value("${nginx.video.path}")
    private String NGINX_DATA_PATH;
    @Value("${upload.absPath}")
    private String absPath;

    private static final String VIDEO_VIEW = "video";
    private static final String VIDEO_ADD = "videoAdd";

    private static final String IP = "http://192.168.1.31";


    /**
     * 分页查询所有数据
     *
     * @param page 分页对象
     * @return 所有数据
     */
    @RequestMapping("list")
    public String list(Page<MovieVideo> page, ModelMap map) {
        initView(map, page, new PageBean());
        return VIDEO_VIEW;
    }

    private void initView(ModelMap map, IPage<MovieVideo> page, PageBean pager) {
        PageHelper.startPage(((int) page.getCurrent()), ((int) page.getSize()));
        List<MovieVideo> movieVideos = movieVideoService.listByPage();

        //封装分页后的数据信息
        PageInfo<MovieVideo> pageInfo = new PageInfo<>(movieVideos);

        pager.setTotalRows(((int) pageInfo.getTotal()));
        pager.setPageRow(pageInfo.getPageSize());
        map.addAttribute("videos", pageInfo.getList());
        map.addAttribute("pager", pager);
    }


    /**
     * 通过主键查询单条数据
     *
     * @param id 主键
     * @return 单条数据
     */
    @RequestMapping("{id}")
    public String selectOne(@PathVariable Serializable id) {
        movieVideoService.getById(id);
        return VIDEO_VIEW;
    }

    /**
     * 新增/修改数据
     *
     * @param movieVideo 实体对象
     * @param file       视频文件
     * @return 新增结果
     */
    @RequestMapping("save")
    public String insert(
            @Valid MovieVideo movieVideo,
            @RequestParam(value = "file", required = false) MultipartFile file,
            ModelMap map
    ) throws IOException {
        if (Objects.nonNull(file)) {
            if (!MediaUtil.isVideo(file)) {
                return "error";
            }
            String videoName = UUID.randomUUID().toString();
            movieVideo.setUrl(IP + "/video/" + videoName + MediaUtil.getExtendName(file));
            String videoPath = NGINX_DATA_PATH + videoName + MediaUtil.getExtendName(file);
            file.transferTo(new File(videoPath));
            //截取视频缩略图
            String coverImageUrl = MediaUtil.generateVideoCoverImage(videoPath);
            movieVideo.setCoverImage(coverImageUrl);
        }
        Manager mgr = ContextUtils.getManagerInfo();
        movieVideo.setCreatetime(Timestamp.from(Instant.now()));
        movieVideo.setUid(mgr.getManagerId());
        movieVideoService.saveOrUpdate(movieVideo);

        initView(map, PageUtil.getDefaultPageConfig(), new PageBean());

        return VIDEO_VIEW;
    }

    @RequestMapping("add")
    public String PageAdd(ModelMap map) {
        List<MovieVo> movies = movieService.list();
        map.addAttribute("movies", movies);
        return VIDEO_ADD;
    }

    @RequestMapping("update")
    public String PageUpdate(
            @RequestParam("vid") long vid,
            ModelMap map
    ) {
        List<MovieVo> movies = movieService.list();
        MovieVideo mv = movieVideoService.getById(vid);
        map.addAttribute("movies", movies);
        map.addAttribute("video", mv);
        return VIDEO_ADD;
    }

    /**
     * 删除数据
     *
     * @param idList 主键结合
     * @return 删除结果
     */
    @RequestMapping("del")
    public String delete(@RequestParam("ids") List<Long> idList, ModelMap map) {
        Collection<MovieVideo> movieVideos = movieVideoService.listByIds(idList);
        //删除视频文件和图片文件
        for (MovieVideo movieVideo : movieVideos) {
            String videoName = getRealFileName(movieVideo.getUrl());
            File video = new File(NGINX_DATA_PATH + videoName);
            if (video.exists()){
                video.delete();
            }
            String imageName = getRealFileName(movieVideo.getCoverImage());
            File coverImage = new File(absPath + imageName);
            if (coverImage.exists()){
                coverImage.delete();
            }
        }
        movieVideoService.removeByIds(idList);
        initView(map, PageUtil.getDefaultPageConfig(), new PageBean());
        return VIDEO_VIEW;
    }

    private String getRealFileName(String url) {
        return url.substring(url.lastIndexOf("/") + 1);
    }

}